package gmomo.test.gui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;

public class LazyLoginDialog extends JDialog implements ActionListener, ItemListener {

	private static final long serialVersionUID = 6240781036904840935L;
	
	private JLabel lblUid;
	private JLabel lblPwd;
	private JPasswordField txtPwd;
	private JButton btnLogin;
	
	private JComboBox cmbUid;
	private JComboBox cmbResource;
	private final String uid[] = {"sandsbot", "sandsmteam"};
	private final String pwd[] = {"sandsand", "sandssands"};
	private final String resource[] = {"sharedmind", "test"};
	
	private MainFrame main;
	
	public LazyLoginDialog(MainFrame main){
		super(main, "Login Dialog", ModalityType.APPLICATION_MODAL);
		this.main = main;
		setup();
	}
	
	private void setup() {
		Container contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());
		JPanel center = new JPanel( new GridLayout(3,3) );
		JPanel btm = new JPanel();
		
		lblUid = new JLabel("Username");
		cmbUid = new JComboBox(uid);
		cmbUid.setEditable(true);
		cmbUid.setSelectedIndex(0);
		cmbUid.addItemListener(this);
		
		cmbResource = new JComboBox(resource);
		cmbResource.setEditable(true);
		cmbResource.setSelectedIndex(0);
		
		lblPwd = new JLabel("Password");
		txtPwd = new JPasswordField(pwd[0]);
		txtPwd.setEchoChar('*');
		btnLogin = new JButton("Login");
		btnLogin.addActionListener(this);
		
		center.add(lblUid);
		center.add(cmbUid);
		center.add(lblPwd);
		center.add(txtPwd);
		
		btm.add(btnLogin);
		contentPane.add( center, BorderLayout.CENTER );
		contentPane.add( btm, BorderLayout.SOUTH );
		
		setPreferredSize( new Dimension( 300, 130 ) );
		setLocation(main.getX(), main.getY());
		
		pack();
		setVisible(true);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		
	}

	public void actionPerformed(ActionEvent e) {
		if ( e.getSource() == btnLogin ) {
			String uid = (String)cmbUid.getSelectedItem();
			
			StringBuffer buffer = new StringBuffer();
			buffer.append(txtPwd.getPassword());
			String pwd = buffer.toString();
			
			String resource = (String)cmbResource.getSelectedItem();
			
			main.login(uid, pwd, resource);
			setVisible(false);
		}
	}

	public void itemStateChanged(ItemEvent e) {
		if ( e.getSource() == cmbUid ) {
			int index = cmbUid.getSelectedIndex();
			if ( index >= 0 )
				txtPwd.setText( pwd[index] );
		}
	}
}
